package com.jiesen.base.config.shiro;

import com.jiesen.base.baseDao.RedisServiceImpl;
import com.jiesen.base.modules.login.jsLoginUser.model.JsLoginUser;
import com.jiesen.base.modules.login.jsRole.model.JsRole;
import com.jiesen.base.modules.login.jsPermission.model.Permission;
import com.jiesen.base.modules.login.jsLoginUser.service.JsLoginUserService;
import com.jiesen.base.modules.login.jsRole.service.JsRoleService;
import com.jiesen.base.utils.JWTUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created with IntelliJ IDEA
 *
 * @Author yuanhaoyue swithaoy@gmail.com
 * @Description 自定义 Realm
 * @Date 2018-04-09
 * @Time 16:58
 */
@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private JsLoginUserService userService;

    @Autowired
    private JsRoleService roleService;

    @Autowired
    private RedisServiceImpl redisService;

    /**
     * 必须重写此方法，不然会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("————身份认证方法————");
        String token = (String) authenticationToken.getCredentials();
        if(token==null){
            return new SimpleAuthenticationInfo(token, token, "MyRealm");
        }

        // 解密获得userId，用于和数据库进行对比
        String userId = JWTUtil.getUserId(token);
        if (userId == null || !JWTUtil.verify(token, userId)) {
            throw new AuthenticationException("token认证失败！");
        }

        JsLoginUser user = (JsLoginUser)redisService.get(token);

        if (user == null) {
            throw new AuthenticationException("该用户不存在！");
        }
        int lock = user.getLock();
        if (lock != 1) {
            throw new AuthenticationException("该用户不能使用！");
        }
        return new SimpleAuthenticationInfo(token, token, "MyRealm");
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("————权限认证————");
        String token = principals.toString();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Set<String> roleSet = new HashSet();
        Set<String> permissionSet = new HashSet();

        //获得该用户以及角色
        JsLoginUser users = (JsLoginUser)redisService.get(token);

        //获得该用户的角色
        List<JsRole> jsRoles = users.getJsRoles();

        //每个角色拥有的权限
        for (JsRole jsRole : jsRoles) {
            List<Permission> permissions = jsRole.getPermissions();
            //放入角色名称
            roleSet.add(jsRole.getName());
            //放入角色拥有的权限
            for (Permission permission : permissions) {
                if(!permissionSet.add(permission.getPercode())){
                    continue;
                }
            }
        }

        //设置该用户拥有的角色和权限
        info.setRoles(roleSet);
        //存放所有权限
        info.setStringPermissions(permissionSet);

        return info;
    }
}
